package com.mhz.mvc.fc;

import java.io.InputStream;
import java.util.List;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.mhz.interceptor.Interceptor;
import com.mhz.mvc.cfg.ActionCfg;
import com.mhz.mvc.cfg.Cfg;
import com.mhz.mvc.cfg.InterceptorCfg;
import com.mhz.mvc.cfg.ResultCfg;
import com.mhz.result.Result;
/**
 * 前端控制器
 * @author mhz
 *
 */
public class FC extends HttpServlet {
	private Cfg config;

	@Override
	public void init(ServletConfig servletCfg) throws ServletException {
		InputStream is = FC.class.getClassLoader().getResourceAsStream(
				"mymvc.xml");
		config = Cfg.getInstance(is);
	}

	@Override
	public void service(HttpServletRequest request, HttpServletResponse response) {
		try {
			String uri = request.getRequestURI();
			String name = uri.substring(uri.lastIndexOf("/") + 1, uri
					.lastIndexOf(".php"));
			ActionCfg actionCfg = config.getActionCfg(name);
			String className = actionCfg.getClassPath();

			// 创建action
			Action action = (Action) Class.forName(className).newInstance();
			// 创建值栈
			ValueStack vs = new ValueStack();
			request.setAttribute("vs", vs);
			//创建action代理
			ActionProxy actionProxy = new ActionProxy(action, vs);
			//创建拦截器
			List<InterceptorCfg> ins = actionCfg.getInterceptorCfgs();
			for (InterceptorCfg inCfg : ins) {
				String inClassName = inCfg.getClazz();
				Interceptor in = (Interceptor) Class.forName(inClassName)
						.newInstance();
				in.setRequest(request);
				in.setResponse(response);
				in.setValueStack(vs);
				actionProxy.pushInterceptor(in);
			}
			
			String resultName = actionProxy.execute();
			ResultCfg resultCfg = actionCfg.getResultCfg(resultName);
			String path = resultCfg.getValue();
			String type = resultCfg.getType();
			Result.getInstance(type, path).execute(
					new MVCRequestWrapper(request), response);

		} catch (Exception e) {
			e.printStackTrace();
		}

	}
}
